import * as React from 'react';
import { injectable, postConstruct, inject } from 'inversify';
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
import { MessageService } from '@theia/core/lib/common/message-service';
import { WidgetManager, ApplicationShell } from '@theia/core/lib/browser';
import { WebviewWidget } from './webview-widget';
import { Tool, TOOLS_WIDGET_FACTORY_ID } from '../common/tools-types';
import { Message } from '@lumino/messaging';
import './style/tools.css';

@injectable()
export class ToolsWidget extends ReactWidget {

    static readonly FACTORY_ID = TOOLS_WIDGET_FACTORY_ID;
    static readonly LABEL = 'Tools Collection';

    @inject(MessageService)
    protected readonly messageService!: MessageService;

    @inject(WidgetManager)
    protected readonly widgetManager!: WidgetManager;

    @inject(ApplicationShell)
    protected readonly shell!: ApplicationShell;

    private tools: Tool[] = [
        {
            id: 'tool1',
            name: '文献检索系统',
            url: 'http://10.12.200.17/ISQS/',
            icon: 'codicon codicon-tools'
        },
    ];

    constructor() {
        super();
        console.log('ToolsWidget constructor called');
    }

    @postConstruct()
    protected init(): void {
        console.log('ToolsWidget init called');

        this.id = TOOLS_WIDGET_FACTORY_ID;
        this.title.label = ToolsWidget.LABEL;
        this.title.caption = 'Development Tools Collection';
        this.title.iconClass = 'codicon codicon-tools';
        this.title.closable = true;

        // 设置Widget为可聚焦
        this.node.setAttribute('tabindex', '0');
        this.node.style.outline = 'none';

        this.update();
        console.log('ToolsWidget init completed');
    }

    protected render(): React.ReactNode {
        console.log('ToolsWidget render called');

        return (
            <div className='tools-container'>
                <div className='tools-header'>
                    <h3>开发工具集</h3>
                </div>
                <div className='tools-list'>
                    {this.tools.map(tool => (
                        <div
                            key={tool.id}
                            className='tool-item'
                            onClick={() => this.openTool(tool)}
                            title={tool.description || tool.name}
                            tabIndex={0}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter' || e.key === ' ') {
                                    e.preventDefault();
                                    this.openTool(tool);
                                }
                            }}
                        >
                            <div className='tool-icon'>
                                <i className={tool.icon || 'codicon codicon-globe'}></i>
                            </div>
                            <div className='tool-content'>
                                <div className='tool-name'>{tool.name}</div>
                                {tool.description && (
                                    <div className='tool-description'>{tool.description}</div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        );
    }

    private async openTool(tool: Tool): Promise<void> {
        console.log('Opening tool:', tool);
        try {
            const widget = await this.widgetManager.getOrCreateWidget(
                WebviewWidget.FACTORY_ID,
                { id: `webview-${tool.id}`}
            ) as WebviewWidget;
            widget.setTool(tool);
            // 确保添加并激活
            if (!widget.isAttached) {
                this.shell.addWidget(widget, { area: 'main' });
            }
            this.shell.activateWidget(widget.id);

        } catch (error) {
            console.error('Error opening tool:', error);
            let errorMessage = '未知错误';

            if (error instanceof Error) {
                errorMessage = error.message;
            } else if (typeof error === 'string') {
                errorMessage = error;
            } else {
                errorMessage = String(error);
            }

            this.messageService.error(`打开工具失败: ${errorMessage}`);
        }
    }

    protected onActivateRequest(msg: Message): void {
        super.onActivateRequest(msg);
        console.log('ToolsWidget activated');
        this.node.focus();
    }

    protected onAfterAttach(msg: Message): void {
        super.onAfterAttach(msg);
        console.log('ToolsWidget attached to DOM');
        this.node.setAttribute('tabindex', '0');
    }

}
